package pay

import (
    "strconv"
	"dhfshop/utils/math"
	"dhfshop/models/member"
	"dhfshop/models/isv"
	"dhfshop/utils/helper"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
	"github.com/pkg/errors"
	"github.com/astaxie/beego"
	wxpay "wxsdk/wxpay/companypay"
)

// 企业支付管理
type CompanyPayController struct {
	base.BaseController
}

/***********支付到零钱*******************/
func (this *CompanyPayController) Transfer() {
	rpcSecretCfg := beego.AppConfig.String("RpcSecret")
	var (
		curOpenId  string = ""
		curAppId   string = ""
	)
	v := struct {
	    CheckName  string  `form:"check_name" valid:"Required"`
	    ReUserName string  `form:"re_user_name" valid:"Required"`
		OrderId    string  `form:"order_id"     valid:"Required"`
		Payment    float32 `form:"payment"      valid:"Required"`
		Desc       string  `form:"desc"         valid:"Required"`
		RpcSecret  string  `form:"rpc_secret"   valid:"Required"`
		AppId      string  `form:"app_id"`
		OpenId     string  `form:"open_id"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	if v.RpcSecret != rpcSecretCfg {
	    this.ServeError("this api is call in internal")
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curRoleId == 1 {
	    curAppId = this.Ctx.Input.GetData("curAppId").(string)
		if members, err := member.GetMemberById(curUserId); err != nil {
			this.ServeError("GetMemberById:" + err.Error())
			return
		}else{
		    curOpenId = members.OpenID
		}
	}else if curRoleId == 2{
	    if len(v.AppId) < 3 {
		    this.ServeError("app_id is invalid")
			return
		}
		curAppId = v.AppId
		if len(v.OpenId) < 3 {
		    this.ServeError("open_id is invalid")
			return
		}
		curOpenId = v.OpenId
	}else{
	    this.ServeError("cur login role is invalid")
		return
	}
	acPay, err := isv.GetParamsByAppIdOrSubAppId(curAppId)
	if err != nil {
		err = errors.Wrap(err, "GetParamsByAppIdOrSubAppId... ")
		this.ServeError(err.Error())
		return
	}
	if acPay.MchTypeId == 2 {
		acPay.AppId = curAppId
		acPay.MchId = acPay.SecondMchId
		acPay.Appkey = acPay.SecondAppkey
		acPay.PemCert = acPay.SecondPemCert
		acPay.PemKey = acPay.SecondPemKey
	}
	paymentStr := strconv.FormatInt(math.MultiTotalPriceInt(v.Payment, 100), 10)
	spbillCreateIP,  _:= helper.GetExternal()
	//beego.Debug("Transfer acPay.AppId:", acPay.AppId, "acPay.MchId:", acPay.MchId)
	//beego.Debug("Transfer acPay.PemCert:", acPay.PemCert)
	//beego.Debug("Transfer acPay.PemKey:", acPay.PemKey)
	transferResponse, err := wxpay.Transfer(acPay.AppId,acPay.MchId,acPay.Appkey,v.OrderId,curOpenId,v.CheckName,v.ReUserName,
	                                        paymentStr,v.Desc,spbillCreateIP,acPay.PemCert,acPay.PemKey)
	if err != nil {
		err = errors.Wrap(err, "Transfer... ")
		this.ServeError(err.Error())
		return 
	}
	this.Data["json"] = transferResponse
	this.ServeJSON()
}

func (this *CompanyPayController) GetTransferInfo() {
	var (
		err        error
		acPay      *isv.AcPayParams = nil
	)
	v := struct {
		OrderId    string  `form:"order_id"     valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if curRoleId == 1 {
	    curAppId := this.Ctx.Input.GetData("curAppId").(string)
		acPay, err = isv.GetParamsByAppIdOrSubAppId(curAppId)
		if err != nil {
			err = errors.Wrap(err, "GetParamsByAppIdOrSubAppId... ")
			this.ServeError(err.Error())
			return
		}
	}else{
	    this.ServeError("cur login role is invalid")
		return
	}									
	gettransferinfoRsp, err := wxpay.Gettransferinfo(acPay.AppId,acPay.MchId,acPay.Appkey,v.OrderId,acPay.PemCert,acPay.PemKey)
	if err != nil {
		err = errors.Wrap(err, "Gettransferinfo... ")
		this.ServeError(err.Error())
		return 
	}
	this.Data["json"] = gettransferinfoRsp
	this.ServeJSON()
}
/***********支付到银行卡*******************/
func (this *CompanyPayController) PayBank() {
	rpcSecretCfg := beego.AppConfig.String("RpcSecret")
	var (
		err        error
		acPay      *isv.AcPayParams = nil
	)
	v := struct {
	    EncBankNo   string  `form:"enc_bank_no"   valid:"Required"`
		EncTrueName string  `form:"enc_true_name" valid:"Required"`
		BankCode    string  `form:"bank_code"     valid:"Required"`
		OrderId     string  `form:"order_id"      valid:"Required"`
		Payment     float32 `form:"payment"       valid:"Required"`
		Desc        string  `form:"desc"`
		RpcSecret   string  `form:"rpc_secret"   valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	if v.RpcSecret != rpcSecretCfg {
	    this.ServeError("this api is call in internal")
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	if curRoleId == 1 {
	    curAppId := this.Ctx.Input.GetData("curAppId").(string)
		acPay, err = isv.GetParamsByAppIdOrSubAppId(curAppId)
		if err != nil {
			err = errors.Wrap(err, "GetParamsByAppIdOrSubAppId... ")
			this.ServeError(err.Error())
			return
		}
	}else{
	    this.ServeError("cur login role is invalid")
		return
	}
	paymentStr := strconv.FormatInt(math.MultiTotalPriceInt(v.Payment, 100), 10)
	PayBankResponse, err := wxpay.PayBank(acPay.MchId,acPay.Appkey,v.OrderId,v.EncBankNo,v.EncTrueName,
	                                      v.BankCode,paymentStr,v.Desc,acPay.PemCert,acPay.PemKey)
	if err != nil {
		err = errors.Wrap(err, "Transfer... ")
		this.ServeError(err.Error())
		return 
	}
	this.Data["json"] = PayBankResponse
	this.ServeJSON()
}

func (this *CompanyPayController) QueryBank() {
	var (
		err        error
		acPay      *isv.AcPayParams = nil
	)
	v := struct {
		OrderId    string  `form:"order_id"     valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if curRoleId == 1 {
	    curAppId := this.Ctx.Input.GetData("curAppId").(string)
		acPay, err = isv.GetParamsByAppIdOrSubAppId(curAppId)
		if err != nil {
			err = errors.Wrap(err, "GetParamsByAppIdOrSubAppId... ")
			this.ServeError(err.Error())
			return
		}
	}else{
	    this.ServeError("cur login role is invalid")
		return
	}
	queryBankRsp, err := wxpay.QueryBank(acPay.MchId,acPay.Appkey,v.OrderId,acPay.PemCert,acPay.PemKey)
	if err != nil {
		err = errors.Wrap(err, "QueryBank... ")
		this.ServeError(err.Error())
		return 
	}
	this.Data["json"] = queryBankRsp
	this.ServeJSON()
}

